package com.example.coursehub.controller;

import com.example.coursehub.dto.MaterialDTO;
import com.example.coursehub.entity.Chapter;
import com.example.coursehub.entity.Course;
import com.example.coursehub.entity.Material;
import com.example.coursehub.service.MaterialService;
import org.springframework.core.io.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;


@RestController
@RequestMapping("/api/materials")
public class MaterialController {
    
    @Autowired
    private MaterialService materialService;

    private String saveFileToLocal(MultipartFile file, String id) throws IOException {
        String uploadDir = System.getProperty("user.dir") + File.separator + "uploads" + File.separator;
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        String filename = file.getOriginalFilename();
        String fullPath = uploadDir + filename;

        file.transferTo(new File(fullPath));
//        System.out.println("上传路径：" + fullPath);
        return fullPath;
    }


    @PostMapping("/upload")
    public ResponseEntity<?> uploadMaterial(
            @RequestParam("file") MultipartFile file,
            @RequestParam("materialName") String materialName,
            @RequestParam("courseId") String courseId,
            @RequestParam("chapterId") String chapterId,
            @RequestParam(value = "materialLabel", required = false) String materialLabel
    ) throws IOException {

        String id = UUID.randomUUID().toString().substring(0, 10);
        String path = saveFileToLocal(file, materialName);

        // 构造实体并保存数据库
        Material material = new Material();
        material.setMaterialId(UUID.randomUUID().toString());
        material.setMaterialName(file.getOriginalFilename());
        material.setMaterialPath(path);
        material.setUploadTime(Instant.now());

        Course course = new Course();
        course.setCourseId(courseId);
        material.setCourse(course);

        Chapter chapter = new Chapter();
        chapter.setChapterId(chapterId);
        material.setChapter(chapter);

        material.setMaterialLabel(materialLabel);

        materialService.uploadMaterial(material);
        return ResponseEntity.ok("上传成功");
    }

    @GetMapping("/{courseId}/chapter/{chapterId}")
    public List<MaterialDTO> getMaterialsByCourseAndChapter(
            @PathVariable String courseId,
            @PathVariable String chapterId) {

        List<Material> materials = materialService.getMaterialsByCourseAndChapter(courseId, chapterId);

        return materials.stream().map(material -> {
            MaterialDTO dto = new MaterialDTO();
            dto.setMaterialId(material.getMaterialId());
            dto.setMaterialName(material.getMaterialName());
            dto.setMaterialPath(material.getMaterialPath());
            dto.setUploadTime(material.getUploadTime());
            dto.setMaterialLabel(material.getMaterialLabel());

            // 提取 ID 而不是整个对象
            dto.setCourseId(material.getCourse().getCourseId());
            dto.setChapterId(material.getChapter().getChapterId());

            return dto;
        }).toList();
    }


    @GetMapping("/course/{courseId}")
    public List<Material> getByCourse(@PathVariable String courseId) {
        return materialService.getMaterialByCourseId(courseId);
    }

    @CrossOrigin(origins = "http://localhost:8080", methods = {RequestMethod.DELETE})
    @DeleteMapping("/{materialId}")
    public ResponseEntity<?> deleteMaterial(@PathVariable String materialId) {
        Optional<Material> materialOpt = materialService.getMaterialById(materialId);
        if (materialOpt.isEmpty()) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("找不到资料");
        }
        
        Material material = materialOpt.get();
        String filePath = material.getMaterialPath();
        File file = new File(filePath);
        if (file.exists()) {
            boolean deleted = file.delete(); // 尝试删除本地文件
            if (!deleted) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件删除失败");
            }
        }
        materialService.deleteMaterial(materialId);

        return ResponseEntity.ok("删除成功");
    }

    @GetMapping("/{id}/download")
    public ResponseEntity<?> downloadMaterial(@PathVariable String id) {
        Optional<Material> materialOpt = materialService.getMaterialById(id);
        if (materialOpt.isEmpty()) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("找不到资料");
        }
        
        Material material = materialOpt.get();
        File file = new File(material.getMaterialPath());
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        try {
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(material.getMaterialName(), "UTF-8"))
                    .contentLength(file.length())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 获取学生在指定章节中已完成的资料
     * @param userId    学生ID
     * @param chapterId 章节ID
     * @return 已完成的资料列表（含资料名、ID、路径等信息）
     */
    @GetMapping("/student/{userId}/chapter/{chapterId}/completed")
    public ResponseEntity<List<Material>> getCompletedMaterialsByStudentAndChapter(
            @PathVariable String userId,
            @PathVariable String chapterId) {
        List<Material> materials = materialService.findCompletedMaterialsByStudent(userId, chapterId);
        return ResponseEntity.ok(materials);
    }

    /**
     * 更新学生资料学习状态
     * @param userId 学生ID
     * @param materialId 资料ID
     * @param isFinished 是否完成
     * @return 操作结果
     */
    @PutMapping("/student/status")
    public ResponseEntity<?> updateMaterialStatus(
            @RequestParam("userId") String userId,
            @RequestParam("materialId") String materialId,
            @RequestParam("isFinished") boolean isFinished) {

        materialService.updateStudentMaterialStatus(userId, materialId, isFinished);
        return ResponseEntity.ok("学习状态更新成功");
    }

    /**
     * 获取学生学习资料状态
     * @param userId 学生ID
     * @param materialId 资料ID
     * @return 是否已完成（true/false）
     */
    @GetMapping("/student/status")
    public ResponseEntity<Boolean> getMaterialStatus(
            @RequestParam("userId") String userId,
            @RequestParam("materialId") String materialId) {

        boolean isFinished = materialService.getStudentMaterialStatus(userId, materialId);
        return ResponseEntity.ok(isFinished);
    }

}
